package gy.com.sansharescuesystem.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BitmapUtils {
	/**
	 * 更新UI
	 */
	private static final Handler handler = new Handler();
	/**
	 * 线程池
	 */
	public static final ExecutorService threadPoll = Executors.newFixedThreadPool(5);
	/**
	 * 本地的sd卡路径
	 */
	private static final String SD_PATH = Environment
			.getExternalStorageDirectory().getPath();
	/**
	 * 图片在sd卡中的目录
	 */
	private static final String PIC_DIR = "image";
	/**
	 * 加载bitmap
	 */
	public static final int PIC_BITMAP = 2;
	/**
	 * 加载Deawable
	 */
	public static final int PIC_DRAWABLE = 1;
	/**
	 * 软应用，在图片很多时候，不建议用
	 */
	private static final HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<>();

	public static Bitmap getBitmap(String url, Context context) {
		Bitmap bitmap;
		bitmap = getBitmapCache(url);
		if (null == bitmap) {
			bitmap = getBitmapSD(url);
			if (null == bitmap) {
				bitmap = getBitMapFromUrl(url, context);
				saveBitmapCache(url, bitmap);
				saveBitmapSD(context,url, bitmap);
			}
		}
		return bitmap;
	}

	public static void saveBitmapCache(String url, Bitmap bitmap) {
		if (!imageCache.containsKey(url)) {
			imageCache.put(url, new SoftReference<>(bitmap));
		}
	}

	public static Bitmap getBitmapCache(String url) {
		Bitmap bitmap = null;
		if (imageCache.containsKey(url)) {
			bitmap = imageCache.get(url).get();
		}
		return bitmap;
	}

	public static String saveBitmapSD(Context pContext, String url, Bitmap bitmap) {
		File dirFile = new File(FileUtils.getIconDir(pContext));
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		File file = new File(dirFile.getPath() + "/" + url);
		if (file.exists()) {
			file.delete();
		}
		if (null != bitmap) {
			try {
				file.createNewFile();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
						new FileOutputStream(file));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file.getPath();
	}

	public static Bitmap getBitmapSD(String url) {
		Bitmap bitmap = null;
		File file = new File(SD_PATH + "/" + PIC_DIR + "/" + url);
		if (file.exists() && !file.isDirectory()) {
			bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
		}
		return bitmap;
	}

	public static Bitmap getBitmapSD(String url, Context pContext) {
		Bitmap bitmap = null;
		File file = new File(FileUtils.getIconDir(pContext)+ "/" + url);
		if (file.exists() && !file.isDirectory()) {
			bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
		}
		return bitmap;
	}

//	/**
//	 * 获取MD5
//	 *
//	 * @param inputString
//	 * @return
//	 */
//	private static String getMD5Code(String inputString) {
//		if (inputString == null || "".equals(inputString)) {
//			return "";
//		}
//		byte[] btInput = inputString.getBytes();
//		MessageDigest mdInst = null;
//		try {
//			mdInst = MessageDigest.getInstance("MD5");
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		}
//		mdInst.update(btInput);
//		byte[] md = mdInst.digest();
//		StringBuffer sb = new StringBuffer();
//		int val;
//		for (byte i = 0; i < md.length; i++) {
//			val = ((int) md[i]) & 0xff;
//			if (val < 16)
//				sb.append("0");
//			sb.append(Integer.toHexString(val));
//		}
//		return sb.toString();
//	}
//
//	private static String getFileName(String url) {
//		return getMD5Code(url);
//	}

	public static String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss", Locale.US);
		LogUtils.debug("got photo path:" + dateFormat.format(date) + ".jpg");
		return dateFormat.format(date) + ".jpg";
	}


	/**
	 * 检查当前是否有可用网络
	 * 
	 * @param cx
	 * @return
	 */
	public static boolean isNetworkAvailable(Context cx) {
		ConnectivityManager cm = (ConnectivityManager) cx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		return (info != null && info.isConnected());
	}

	public static Bitmap getBitMapFromUrl(String url, Context context) {
		URL myFileUrl;
		Bitmap bitmap = null;
		if (isNetworkAvailable(context) && !TextUtils.isEmpty(url)) {
			try {
				myFileUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) myFileUrl
						.openConnection();
				conn.setConnectTimeout(5000);
				conn.setDoInput(true);
				conn.connect();
				InputStream is = conn.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bitmap;
	}

	/**
	 * Bitmap转换为Drawable
	 * 
	 * @param bitmap
	 * @param context
	 * @return
	 */
	public static Drawable bitmapToDrawable(Bitmap bitmap,
											Context context) {
		BitmapDrawable drawable = null;
		if (null != bitmap && null != context && context instanceof Activity) {
			// bitmap转换为Drawable时会缩小,用下面这种方法可以使其为原来大小
			drawable = new BitmapDrawable(bitmap);
			DisplayMetrics metric = new DisplayMetrics();
			((Activity) context).getWindowManager().getDefaultDisplay()
					.getMetrics(metric);
			drawable.setTargetDensity(metric);
		}
		return drawable;
	}

	/**
	*Drawable转Bitmap
	*@author huangbo
	*create at 2016/11/16 16:58
	*/
	public static Bitmap drawableToBitmap(Context pContext, int pDrawableID){
		Resources res = pContext.getResources();
		Bitmap bmp = BitmapFactory.decodeResource(res, pDrawableID);
		return bmp ;
	}

	/**
	*Bitmap转Bytes
	*@author huangbo
	*create at 2016/11/16 16:58
	*/
	public byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	*Bytes转Bimap
	*@author huangbo
	*create at 2016/11/16 16:58
	*/
	public Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

	public static void loadImg(final String url, final ImageView imageView,
							   final Context context, final int type) {
		threadPoll.submit(new Runnable() {
			@Override
			public void run() {
				try {
					final Bitmap bitmap = getBitmap(url, context);
					if (null != bitmap) {
						handler.post(new Runnable() {
							@Override
							public void run() {
								if (type == PIC_BITMAP) {
									imageView.setImageBitmap(bitmap);
								}
								if (type == PIC_DRAWABLE) {
									imageView.setBackgroundDrawable(BitmapUtils
											.bitmapToDrawable(bitmap,
													context));
								}
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	public static Bitmap decodeUriAsBitmap(Uri uri, Context pContext){
		Bitmap bitmap;
		try {
			bitmap = BitmapFactory.decodeStream(pContext.getContentResolver().openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}
}
